<script>
import {getDetailInfo, getGroupList, getGroupName, updateUser} from '@/api/user'

function checkPhone(rule, value, callback) {
  const reg = /^\d{11}$/
  if (!reg.test(value)) {
    callback(new Error(this.$t('user_phone_rule')))
  } else {
    callback()
  }
}

function newForm() {
  return {
    id: 0,
    name: '',
    telephone: '',
    email: '',
    groupId: 1
  }
}

export default {
  name: 'UserEditPage',
  data() {
    return {
      groupList: [],
      form: {
        name: '',
        telephone: '',
        email: '',
        groupId: '',
        groupName: '',
        avatar: 0 
      },
      avatarList: [
        require('@/assets/avatars/1.jpg'),
        require('@/assets/avatars/2.jpg'),
        require('@/assets/avatars/3.jpg'),
        require('@/assets/avatars/4.jpg'),
        require('@/assets/avatars/5.jpg'),
        require('@/assets/avatars/6.jpg'),
        require('@/assets/avatars/7.jpg'),
        require('@/assets/avatars/8.jpg'),
        require('@/assets/avatars/9.jpg'),
        require('@/assets/avatars/10.jpg'),
        require('@/assets/avatars/11.jpg'),
        require('@/assets/avatars/12.jpg'),
        require('@/assets/avatars/13.jpg'),
        require('@/assets/avatars/14.jpg'),
        require('@/assets/avatars/15.jpg'),
        require('@/assets/avatars/16.jpg'),
        require('@/assets/avatars/17.jpg'),
        require('@/assets/avatars/18.jpg'),
        require('@/assets/avatars/19.jpg'),
        require('@/assets/avatars/20.jpg'),
      ],
      rules: {
        name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: this.$t('user_phone_rule'), trigger: 'blur' },
          { type: 'number', validator: checkPhone, message: '请填写正确手机号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        groupId: [
          { required: true, message: '请选择用户组', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    // 计算属性过滤掉 id=1 的用户组（管理员）
    filteredGroupList() {
      return this.groupList.filter(g => g.id !== 1);
    }
  },
  created() {
    // 添加权限校验逻辑
    if (!this.$store.getters.isAdmin()) {
      this.$message({
        type: 'error',
        message: '您没有权限访问此页面'
      });
      this.$router.push('/'); 
      return;
    }
    this.getData()
  },
  methods: {
    getData() {
      this.listLoading = true
      // 加载组列表数据
      getGroupList().then(response => {
          this.groupList = response.data
        })
      // 加载用户数据回显
      this.loadUserInfo();

    },
    getGroupName(group_id) {
      for (var i = 0; i < this.groupList.length; i++) {
        if (group_id === this.groupList[i].id) {
          return this.groupList[i].name
        }
      }
    },

    loadUserInfo() {
      // 根据id加载用户数据
      getDetailInfo(this.$route.params.id).then(res => {
        this.form = {
          id: res.data.id,
          name: res.data.name,
          telephone: res.data.telephone,
          email: res.data.email,
          groupId: res.data.group_id,
          groupName: this.getGroupName(res.data.group_id),
          avatar: res.data.avatar
        }
      })
    },
    selectAvatar(index) {
      this.form.avatar = index;
    },
    cancelEdit() {
      this.$router.push({ path: '/configuration/user' })
    },
    onEdit() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          this.$message({
            type: 'warning',
            message: '请检查输入内容是否符合要求'
          });
          return;
        }

        updateUser(this.form).then(response => {
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: '账户信息已保存'
            });
            this.form = newForm();
            this.formVisible = false;
            this.getData(1);
          } else {
            this.$message({
              type: 'error',
              message: response.message
            });
          }
        })
      });
    },
  }
}
</script>

<template>
  <div class="edit-user-page">
    <div class="create-container">
      <el-form ref="form" :model="form" :rules="rules" inline-message="true">
        <el-form-item :label="$t('user') + $t('type')" label-width="120px" prop="groupId">
          <el-select v-model="form.groupId" style="width: 250px;" :disabled="!($store.getters.isAdmin())">
            <el-option v-for="(g, index) in filteredGroupList" :key="index" :label="g.name" :value="g.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('nickname')" label-width="120px" prop="name">
          <el-input v-model="form.name" autocomplete="off" style="width: 250px;"/>
        </el-form-item>
        <el-form-item :label="$t('telephone')" label-width="120px" prop="telephone">
          <el-input v-model="form.telephone" autocomplete="off" style="width: 250px;"/>
        </el-form-item>
        <el-form-item :label="$t('email')" label-width="120px" prop="email">
          <el-input v-model="form.email" autocomplete="off" style="width: 250px;"/>
        </el-form-item>
        <el-form-item :label="$t('avatar')" label-width="120px">
          <el-image :src="avatarList[form.avatar]" fit="cover" style="width: 100px; height: 100px;"></el-image>
          <div class="avatar-grid" v-if="avatarList.length > 0">
            <el-image
              v-for="(avatarUrl, index) in avatarList"
              :key="index"
              :src="avatarUrl"
              fit="cover"
              style="width: 50px; height: 50px;"
              @click="selectAvatar(index)"
            >
            </el-image> 
          </div>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <!-- <el-button @click="cancelEdit">{{ $t('cancel') }}</el-button> -->
        <el-button type="primary" @click="onEdit">{{ $t('save') }}</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.edit-user-page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.dialog-footer {
  text-align: left;
  margin-left: 120px;
  margin-top: 20px;
}
.avatar-grid {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
  gap: 30px; /* 间距 */
}

.create-container {
  width: 100%;
  max-width: 1000px;
  padding: 20px;
  border-left: 1px solid #DCDFE6;
  border-radius: 4px !important;
  background-color: #fff;
}
</style>